const express = require('express')
const compression = require('compression')
const fs = require('fs')
const app = express()

app.use(compression());

//打包渲染器
const { createBundleRenderer } = require('vue-server-renderer');

const bundle = require('../dist/server/vue-ssr-server-bundle.json');
const clientManifest = require('../dist/client/vue-ssr-client-manifest.json');

//工厂
const renderer = createBundleRenderer(bundle, {
    runInNewContext: false,
    template: fs.readFileSync('../src/index.temp.html', 'utf-8'),
    clientManifest:clientManifest
})

function renderToString(context) {
    return new Promise((resolve, reject) => {
        renderer.renderToString(context, (err, html) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(html);
        })
    })
}

app.use(express.static('../dist/client'))

app.get('*', async function (req, res) {
    try {
        const context = {
            url: req.url
        }
        const html = await renderToString(context);
        res.send(html)
    } catch (error) {
        res.status(500).send('请从首页进入');
    }
})

app.listen(3000,()=>{
    console.log('启动成功');
})






